package com.example.contactapp;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;


public class LoginActivity extends AppCompatActivity {
    private DatabaseHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        dbHelper = new DatabaseHelper(this);

        // 获取 UI 组件
        EditText loginUsernameEdittext = (EditText) findViewById(R.id.username_edittext);
        EditText loginPasswordEdittext = (EditText) findViewById(R.id.password_edittext);
        Button loginButton = (Button) findViewById(R.id.login_button);

        // 设置点击事件
        loginButton.setOnClickListener(view -> {
            // 获取输入的用户名和密码
            String username = loginUsernameEdittext.getText().toString().trim();
            String password = loginPasswordEdittext.getText().toString().trim();

            // 检查输入是否为空
            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(LoginActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            // 查询用户数据
            boolean userExists = dbHelper.getUserByUsernameAndPassword(username, password);

            if (userExists) {
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                // 跳转到主页面或其他页面
                Intent intent = new Intent(LoginActivity.this, MainActivity2.class);
                intent.putExtra("username",username);
                startActivity(intent);
            } else {
                Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void goRegistry(View view){
        Intent intent = new Intent(LoginActivity.this,RegistryActivity.class);
        startActivity(intent);
    }
}